import logging, json

from bs4 import BeautifulSoup
from django.db import transaction
from django.db.models import F

from forum.models import Attachments, TopicThumb, TopicFollow, BoardTopic
from user_app.models import AccountInfo, AccountFollow
from utils import query_utils
from utils.common_utils import json_response, Pagination
from utils.decorators import json_check, check_login, get_token_info

logger = logging.getLogger(__name__)
error_logger = logging.getLogger("error")


@check_login
@json_check
def post_board(request, json_data):
    # 发布品牌
    phone = request.session['phone']
    account = AccountInfo.objects.get(mobile_phone=phone)

    subject = json_data.get("subject")
    banner_image = json_data.get("banner_image")
    cover_image = json_data.get("cover_image")
    company_info = json_data.get("company_info")
    product_info = json_data.get("product_info")
    develop = json_data.get("develop")
    case = json_data.get("case")
    attachments_ids = json_data.get("attachments_ids")

    flag, msg = query_utils.check_allow_post(account.id)
    if flag:
        return json_response({"code": 1000, "message": msg})

    bt = BoardTopic()
    bt.subject = subject
    bt.banner_image = banner_image
    bt.cover_image = cover_image
    bt.company_info = company_info
    bt.product_info = json.dumps(product_info)
    bt.develop = json.dumps(develop)
    bt.case = json.dumps(case)

    bt.account_info = account
    bt.last_post_account_id = None
    bt.save()
    bt.refresh_from_db()
    at = Attachments.objects.filter(id__in=attachments_ids, topic_id=0)
    if at:
        at.update(topic_id=bt.id, category=2)
    result_dict = {
        "boardid": bt.id
    }
    return json_response({"code": 0, "message": "发布成功", "data": result_dict})


@get_token_info
def get_board_list(request):
    account_id = request.session.get('account_id', '')
    # 首页获取品牌列表
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    topic_count = BoardTopic.objects.filter(check_status=1).count()
    p = Pagination(page=page, per_page=per_page, total=topic_count)
    topic_list = BoardTopic.objects.filter(check_status=1).order_by("-created_on")[p.offset:p.offset + per_page]
    result_list = []
    for item in topic_list:
        soup = BeautifulSoup(item.company_info, 'html.parser')
        parser_content = soup.get_text()[:80]

        tmp = {
            "id": item.id,
            "subject": item.subject,
            "banner_image": item.banner_image,
            "cover_image": item.cover_image,
            "content": parser_content,
            # "product_info": item.product_info,
            # "develop": item.develop,
            # "case": item.case,
            "numreplies": item.num_replies,
            "numthumb": item.num_thumb,
            "numviews": item.num_views,
            "level": item.level,
            "accountid": item.account_info.id,
            "account": item.account_info.nick_name,
            "avatar": item.account_info.avatar,
            "lastpost": "",
            "lastreplyon": item.created_on,
            "accountisfollow": AccountFollow.objects.filter(created_by_id=account_id, follow_account_id=item.account_info.id).exists() if account_id else False,
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@get_token_info
def get_board_detail(request):
    account_id = request.session.get('account_id', '')
    topic_id = request.GET.get('board_id', '')
    try:
        topic = BoardTopic.objects.get(id=topic_id)
        soup = BeautifulSoup(topic.company_info, 'html.parser')
        parser_content = soup.get_text()[:50]
        result_dict = {
            "id": topic.id,
            "subject": topic.subject,
            "banner_image": topic.banner_image,
            "cover_image": topic.cover_image,

            "company_info": topic.company_info,
            "product_info": json.loads(topic.product_info),
            "develop": json.loads(topic.develop),
            "case": json.loads(topic.case),
            "numreplies": topic.num_replies,
            "numthumb": topic.num_thumb,
            "numviews": topic.num_views,
            "level": topic.level,
            "hidden": topic.hidden,

            "accountid": topic.account_info.id,
            "account": topic.account_info.nick_name,
            "accountisfollow": AccountFollow.objects.filter(created_by_id=account_id, follow_account_id=topic.account_info.id).exists() if account_id else False,
            "avatar": topic.account_info.avatar,
            "time": topic.created_on,
            "isthumb": TopicThumb.objects.filter(topic_id=topic.id, created_by_id=account_id, category=2).exists() if account_id else False,
            "isfollow": TopicFollow.objects.filter(follow_topic_id=topic.id, created_by_id=account_id, category=2).exists() if account_id else False,
            #"recentlytopic": __get_account_recently_topic(topic.account_info.id, topic_id),
            "parser_content": parser_content
        }
        topic.num_views = F('num_views') + 1
        topic.save(update_fields=['num_views'])
        # topic.refresh_from_db()
        return json_response({"code": 0, "message": "", "data": result_dict})
    except BoardTopic.DoesNotExist:
        return json_response({"code": 1000, "message": "品牌信息不存在！"})


@check_login
def board_thumb(request):
    # 点赞/取消赞接口
    account_id = request.session['account_id']
    topic_id = request.GET.get('board_id')
    flag, tc = __check_board(topic_id)
    if not flag:
        return json_response({"code": 1000, "message": "品牌信息不存在"})
    thumb = TopicThumb.objects.filter(created_by_id=account_id, topic_id=topic_id, category=2)
    result_dict = {

    }
    if thumb:
        thumb.delete()
        result_dict['flag'] = False
        topic = tc[0]
        topic.num_thumb = F('num_thumb') - 1
        topic.save(update_fields=['num_thumb'])
        return json_response({"code": 0, "message": "取消点赞", "data": result_dict})
    else:
        tb = TopicThumb()
        tb.topic_id = topic_id
        tb.topic_account_id = tc[0].account_info.id
        tb.created_by_id = account_id
        tb.category = 2
        tb.save()
        result_dict['flag'] = True
        topic = tc[0]
        topic.num_thumb = F('num_thumb') + 1
        topic.save(update_fields=['num_thumb'])
        return json_response({"code": 0, "message": "点赞成功", "data": result_dict})


@check_login
def board_follow(request):
    # 活动收藏接口
    account_id = request.session['account_id']
    topic_id = request.GET.get('board_id')
    flag, tc = __check_board(topic_id)
    if not flag:
        return json_response({"code": 1000, "message": "品牌信息不存在"})
    if account_id == tc[0].account_info.id:
        return json_response({"code": 1000, "message": "无法收藏自己发布的品牌信息"})
    follow = TopicFollow.objects.filter(created_by_id=account_id, follow_topic_id=topic_id, category=2)
    result_dict = {

    }
    if follow:
        follow.delete()
        result_dict['flag'] = False
        return json_response({"code": 0, "message": "取消收藏", "data": result_dict})
    else:
        fw = TopicFollow()
        fw.follow_topic_id = topic_id
        fw.topic_account_id = tc[0].account_info.id
        fw.created_by_id = account_id
        fw.category = 2
        fw.save()
        result_dict['flag'] = True
        return json_response({"code": 0, "message": "收藏成功", "data": result_dict})


def __check_board(topic_id):
    tc = BoardTopic.objects.filter(id=topic_id)
    if not tc:
        return False, tc
    return True, tc
